//
//  YD_publish_conversations.m
//  SpeedDating
//
//  Created by isu on 17/1/14.
//  Copyright © 2017年 isu. All rights reserved.
//

#import "Friendconversations.h"
//文字输入框
#import "HSLimitText.h"
#import "FriendpublishVedioCell.h"
#import "FriendlocationConversationCell.h"
#import "FriendpublishConversationCell.h"

#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
//选择位置
#import "FriendchooseLocationsController.h"
//谁可以看我
#import "FriendWhoLookViewController.h"
//提醒谁看我
#import "FriendRemindWhoController.h"
//照片选择
#import "TZImagePickerController.h"
#import "GGActionSheet.h"
#import "AlertViewExtension.h"


#define SOUND_RECORD_LIMIT 60
#define DocumentPath  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
@interface Friendconversations ()<UITableViewDataSource, UITableViewDelegate,FriendpublishConversationCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,FriendpublishConversationCellDelegate,GGActionSheetDelegate,alertviewExtensionDelegate,HSLimitTextDelegate>

    /* <,
     ,,LGSoundRecorderDelegate> */
{
      CGFloat _textCellHeight;
      CGFloat _cell2H;
     AVPlayerViewController * avPlayer;
     NSString *_locationStr;
    
}
/** base_tableview*/
@property (nonatomic, strong)UITableView *base_tableview;
@property(nonatomic,strong)NSMutableArray *arrM;
/** contentStr*/
@property (nonatomic, strong)NSString *contentStr;
/** commitBtn*/
@property (nonatomic, strong)UIButton *commitBtn;
/** 视频类型时cell高度*/
@property (nonatomic, assign)CGFloat vedioCellH;
/** vedioUrl*/
@property (nonatomic, strong)NSURL *vedioUrl;
/** vedioImageV*/
@property (nonatomic, strong)UIImageView *vedioImageV;

/** recordButton*/
@property (nonatomic, strong) UIButton *recordButton;
/** broadcastBtn*/
@property (nonatomic, strong) UIButton *broadcastBtn;

@property (nonatomic, weak)   NSTimer *timerOf60Second;

/** 存放语音路径*/
@property (nonatomic, strong) NSString *audioPath;
/** 存放语音时长*/
@property (nonatomic, assign) NSTimeInterval seconds;
/** atPersonsStr*/
@property (nonatomic, strong) NSString *atPersonsStr;

@property (nonatomic, strong) NSArray *addUserArray;

@property (nonatomic, assign) NSInteger seeType;


/** 动态公开状态存储 */
@property (nonatomic, strong) NSString *UserShowStr;
/** 存放提醒谁看的字符串*/
@property (nonatomic, strong) NSString *atPersionNameStr;

@property (nonatomic, strong) NSArray *userArray;

@property (nonatomic, strong) GGActionSheet *actionSheetTitle;
@property (nonatomic, strong) AlertViewExtension *alert;
@property (nonatomic, strong) HSLimitText *textView;

@end

@implementation Friendconversations
-(NSMutableArray *)arrM{
    if(_arrM==nil){
        _arrM = [NSMutableArray array];
    }
    return _arrM;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.addUserArray = @[];
    self.userArray = @[];
    self.seeType = 1;
    self.atPersionNameStr = nil;
    self.atPersonsStr = nil;
    _locationStr =  nil;
    self.UserShowStr =nil;
    if(self.takedPhoto){
        [self.arrM addObject:self.takedPhoto];
    }
    _cell2H  =(KScreenWidth-80)*0.25+30;
    [self makeTitle];

    
    UIButton *leftBtn = [UIButton new];
    leftBtn.frame = CGRectMake(0, 0, 40, 40);
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];

    
    
    self.view.backgroundColor =[UIColor whiteColor];
    UIButton *commitBtn = [UIButton new];
    [commitBtn setTitle:@"发送" forState:UIControlStateNormal];
    [commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    commitBtn.frame = CGRectMake(0, 0, 40, 40);
    commitBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [commitBtn addTarget:self action:@selector(clickRitghButton) forControlEvents:UIControlEventTouchUpInside];
    [commitBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:commitBtn];
    [self base_tableviewMake];
    self.commitBtn = commitBtn;
}

- (void)backAction {
    self.alert =[[AlertViewExtension alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth, KScreenHeight)];
    self.alert.delegate=self;
    [self.alert setbackviewframeWidth:KScreenWidth-50 Andheight:110];
    [self.alert settipeTitleStr:@"是否确认放弃编辑" Andfont:14];
    [self.view addSubview:self.alert];
}

-(void)clickBtnSelector:(UIButton *)btn
{
    if (btn.tag == 0) {
        [self.navigationController popViewControllerAnimated:YES];
        [self.alert removeFromSuperview];
    }else{
        [self.alert removeFromSuperview];
    }
}


#pragma mark - clickRitgtButton
-(void)clickRitghButton{
    self.commitBtn.userInteractionEnabled  = NO;
    WEAKSELF
        switch (self.conversation_Type){
            case KConversationWords:  //发布文字
            {
                if(self.contentStr.length==0){
                    [SVProgressHUD showInfoWithStatus:@"发布文字不能为空!"];
                    self.commitBtn.userInteractionEnabled  = YES;
                    return ;
                }
                else{
                    [HcardHttpmanager publishFriendCircleWithType:KAddCircle_wordsType WithContent:self.contentStr WithVideo:nil WithImg:nil WithLocation:_locationStr WithSeetype:_seeType WithSomebody:[_userArray componentsJoinedByString:@","] WithRemind:self.atPersonsStr Success:^(id result) {
                        if(result){
                            [SVProgressHUD showSuccessWithStatus:@"发布状态成功!"];
                            if ([weakSelf.delegate respondsToSelector:@selector(clickFinishButton)]) {
                                [weakSelf.delegate clickFinishButton];
                            }
                            [self.navigationController popViewControllerAnimated:YES];
                            self.commitBtn.userInteractionEnabled  = YES;
                        }else{
                            [SVProgressHUD showErrorWithStatus:@"发布状态失败!"];
                            self.commitBtn.userInteractionEnabled  = YES;
                        }
                    } failure:^(NSError *error) {
                        if(error){
                            [SVProgressHUD showErrorWithStatus:@"发布状态失败!"];
                            self.commitBtn.userInteractionEnabled  = YES;
                        }
                    }];
                    break;
                }
            }
            case KConversationPhoto:  //发布照片
            {
                if(self.arrM.count==0){
                    [SVProgressHUD showInfoWithStatus:@"请选择图片!"];
                    self.commitBtn.userInteractionEnabled  = YES;
                    return ;
                }
                //发请求
                [SVProgressHUD showWithStatus:@"正在发布"];
                [HcardHttpmanager upLoadPhotosWithFileArr:self.arrM WithBelong:@"publishPhotos" WithToAublum:KToAublumNO  WithAlbumId:nil success:^(id sucess) {
                    [SVProgressHUD dismiss];
                    if(sucess){
                        [SVProgressHUD showSuccessWithStatus:@"上传成功!"];
                        NSArray *arr = sucess;
                        NSMutableString *strM = [NSMutableString string];
                        for(int  i = 0 ;i<arr.count;i++){
                            [strM appendString:[NSString stringWithFormat:@"%@,",arr[i]]];
                        }
                        strM= [strM substringToIndex:strM.length-1].copy;
                        [HcardHttpmanager publishFriendCircleWithType:KAddCircle_photoType WithContent:self.contentStr WithVideo:nil WithImg:strM WithLocation:_locationStr WithSeetype:_seeType WithSomebody:[_userArray componentsJoinedByString:@","] WithRemind:self.atPersonsStr Success:^(id result) {
                            if(result){
                                [SVProgressHUD showSuccessWithStatus:@"发布状态成功!"];
                                if ([weakSelf.delegate respondsToSelector:@selector(clickFinishButton)]) {
                                    [weakSelf.delegate clickFinishButton];
                                }
                                [self.navigationController popViewControllerAnimated:YES];
                                self.commitBtn.userInteractionEnabled  = YES;
                            }else{
                                [SVProgressHUD showErrorWithStatus:@"发布状态失败!"];
                                self.commitBtn.userInteractionEnabled  = YES;
                            }
                        } failure:^(NSError *error) {
                            if(error){
                                [SVProgressHUD showErrorWithStatus:@"发布状态失败!"];
                                self.commitBtn.userInteractionEnabled  = YES;
                            }
                        }];
                        
                    }else{
                        [SVProgressHUD showErrorWithStatus:@"发布失败!"];
                        self.commitBtn.userInteractionEnabled  = YES;
                    }
                } failure:^(NSError *error) {
                    if(error){
                        [SVProgressHUD dismiss];
                        [SVProgressHUD showErrorWithStatus:@"发布失败!"];
                        self.commitBtn.userInteractionEnabled  = YES;
                    }
                }];
                break;
            }
            case KConversationVedio:  //发布视频
            {
                if(!self.vedioUrl){
                    [SVProgressHUD showInfoWithStatus:@"请选择视频!"];
                    self.commitBtn.userInteractionEnabled  = YES;
                    return ;
                }
                [SVProgressHUD showWithStatus:@"正在发布"];
                if(self.vedioUrl){
                    UIImage *image = [HcardHttpmanager thumbnailImageForVideo:self.vedioUrl atTime:0.5];
                    [HQHttpManager uploadImageWithImage:image imgBelong:@"thumbnail" successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                        if (isSuccess) {
                            NSString *imgUrl = resultDic[@"res"];
                            [HcardHttpmanager upLoadVideoVideoPath:self.vedioUrl WithBelong:@"friendCicleVedio" uploadSuccess:^(id sucess) {
                                if(sucess){
                                    [SVProgressHUD showSuccessWithStatus:@"发布成功!"];
                                    [HcardHttpmanager publishFriendCircleWithType:KAddCircle_vedioType WithContent:self.contentStr WithVideo:sucess WithImg:imgUrl WithLocation:_locationStr WithSeetype:_seeType WithSomebody:[_userArray componentsJoinedByString:@","] WithRemind:self.atPersonsStr Success:^(id result) {
                                        if(result){
                                            [SVProgressHUD showSuccessWithStatus:@"发布状态成功!"];
                                            if ([weakSelf.delegate respondsToSelector:@selector(clickFinishButton)]) {
                                                [weakSelf.delegate clickFinishButton];
                                            }
                                            [self.navigationController popViewControllerAnimated:YES];
                                            self.commitBtn.userInteractionEnabled  = YES;
                                        }else{
                                            [SVProgressHUD showErrorWithStatus:@"发布状态失败!"];
                                            self.commitBtn.userInteractionEnabled  = YES;
                                        }
                                    } failure:^(NSError *error) {
                                        if(error){
                                            [SVProgressHUD showErrorWithStatus:@"发布状态失败!"];
                                            self.commitBtn.userInteractionEnabled  = YES;
                                        }
                                    }];
                                    
                                }
                                else{
                                    [SVProgressHUD showErrorWithStatus:@"发布失败!"];
                                }
                            } uploadFailure:^(NSError *failure) {
                                [SVProgressHUD showErrorWithStatus:@"发布失败!"];
                            } progress:^(NSProgress *progress) {
                                
                            }];
                        }
                    }];
                }else{
                    [SVProgressHUD dismiss];
                }
                
            }
                break;
            case KConversationAudio:  //发布音频
            {
                
            }
                break;
        }
    }
   

//#pragma mark - base_tableviewMake
-(void)base_tableviewMake{
    self.base_tableview = [UITableView new];
    [self.view addSubview:self.base_tableview];
    if(self.conversation_Type==KConversationAudio){
        [self.base_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(-110);
        }];
     
        
    }else{
        [self.base_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(self.view);
            make.top.mas_equalTo(0);
        }];
    }
    self.base_tableview.delegate=self;
    self.base_tableview.dataSource =self;
    self.base_tableview.backgroundColor =[UIColor clearColor];
    self.base_tableview.tableFooterView =[UIView new];
    self.base_tableview.separatorStyle  = UITableViewCellSeparatorStyleNone;

}


#pragma mark ============tableView delegate======UITableViewDataSource=====
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)tableView:(UITableView *)tableView updatedHeight:(CGFloat)height atIndexPath:(NSIndexPath *)indexPath
{
    _textCellHeight = height;
}
- (void)tableView:(UITableView *)tableView updatedText:(NSString *)text atIndexPath:(NSIndexPath *)indexPath
{
    
}
- (void)tableView:(UITableView *)tableView textViewDidEndEditing:(UITextView*)textView{
    self.contentStr = textView.text;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section==1){
        return 0 ;
    }
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.conversation_Type==KConversationAudio||self.conversation_Type==KConversationWords){
        return section==0?1:3;
    }else{
        return section==0?2:3;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0&&indexPath.row==0){
        return  MAX(120.0, _textCellHeight);
    }else if (indexPath.section==0&&indexPath.row==1){
        if(self.conversation_Type ==KConversationVedio){
            return  self.vedioCellH+20;
        }
        else{
            return _cell2H;
        }
    }else{
        if (indexPath.row == 1) {
            if([self.isTopic isEqualToString:@"topic"]) {
                return 0;
            } else {
                return 50;
            }
        }
        return 50;
    }

}
- (void)limitTextLimitInput:(HSLimitText *)textLimitInput text:(NSString *)text{
    _contentStr = text;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0&&indexPath.row==0){

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellStrCell"];
        
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellStrCell"];
            _textView = [[HSLimitText alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 120) type:TextInputTypeTextView];
            _textView.delegate = self;
            _textView.placeholder = @"此时你在想什么......";
            _textView.labPlaceHolder.textColor = RGB(244, 243, 242);
            
            [cell addSubview:_textView];
        }

        return cell;
    }else if (indexPath.section==0&&indexPath.row==1){
        if(self.conversation_Type ==KConversationVedio){
            FriendpublishVedioCell *cell = [FriendpublishVedioCell cellWithTableView:tableView];
            self.vedioCellH = [cell getHeight];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pickVedio)];
            [cell.vedioImageV addGestureRecognizer:tap];
            self.vedioImageV = cell.vedioImageV;
            cell.vedioImageV.userInteractionEnabled = YES;
            return cell;
        }
        else{
            FriendpublishConversationCell *cell = [FriendpublishConversationCell cellWithTableView:tableView];
            cell.delegate  =self;
            cell.arrPhotos = [self.arrM copy];
            _cell2H = [cell getHeight];
            return cell;
        }
    }else{
        FriendlocationConversationCell *cell = [FriendlocationConversationCell cellWithTableView:tableView];
        cell.tag=indexPath.row;
        

        [cell.tapG addTarget:self action:@selector(TAPCLICK:)];
        if (indexPath.row==0) {
            cell.showLab.text =@"所在位置";
            cell.imageV.image = [UIImage imageNamed:@"Friend_news_placeholder"];
            cell.showLab2.text = _locationStr;
            cell.showLab2.font = FontP(12);
        } else if (indexPath.row == 1) {
            cell.showLab.text = @"谁可以看";
            cell.imageV.image = [UIImage imageNamed:@"Friend_news_eyes"];
            switch (self.seeType) {
                case 1:
                    cell.showLab2.text = @"公开";
                    _UserShowStr = cell.showLab2.text;

                    break;
                case 2:
                    cell.showLab2.text = @"仅自己可见";
                    _UserShowStr = cell.showLab2.text;

                    break;
                case 3:
                    cell.showLab2.text = @"部分可见";
                    _UserShowStr = cell.showLab2.text;

                    break;
                case 4:
                    cell.showLab2.text = @"部分不可见";
                    _UserShowStr = cell.showLab2.text;

                    break;
                default:
                    break;
            }
            if([self.isTopic isEqualToString:@"topic"]) {
                cell.hidden = YES;
            } else {
                cell.hidden = NO;
            }
        } else {
            
            cell.showLab.text = @"提醒谁看";
            cell.imageV.image = [UIImage imageNamed:@"Friend_news_alt"];
            if(self.atPersionNameStr.length!=0){
                cell.showLab2.text= self.atPersionNameStr;
            }
        }
        return cell;
    }
}

//#pragma mark - makeTitle
-(void)makeTitle{
    switch (self.conversation_Type) {
        case KConversationAudio:
            self.title = @"发布音频";
            break;
        case KConversationPhoto:
            self.title = @"发布照片";
            break;
        case KConversationWords:
            self.title = @"发布文字";
            break;
        case KConversationVedio:
            self.title = @"发布视频";
            break;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    
    imagePickerVc.allowPickingVideo = NO;
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    
    [self.arrM addObjectsFromArray:photos];
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:0];
    
    [self.base_tableview reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
}


-(void)publishConversationCellStartGetPhotos{
    WEAKSELF
//    tapClick
    if ( [self.photoType isEqualToString:@"1"]) {
        [weakSelf takePhoto];
    }else{
        [weakSelf pushImagePickerController];

    }
}




- (void)takePhoto {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"该设备不支持拍照功能" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    else
    {
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
        
    }
}

#pragma mark UIImagePickerDelegate



-(void)publishConversationCellStartDelegatePhoto:(NSUInteger)index{
    [self.arrM removeObjectAtIndex:index];
    [self.base_tableview reloadData];
}

#pragma mark =========是否显示位置======谁可以看到我=======提醒谁看我

-(void)TAPCLICK:(UITapGestureRecognizer*)tapG{
    FriendlocationConversationCell *cell = (FriendlocationConversationCell*)[tapG.view superview];
    switch (cell.tag) {
        case 0:{
            
            FriendchooseLocationsController *vc = [FriendchooseLocationsController new];
            vc.blockLocation = ^(NSString *str){
                if(str.length==0){
                    _locationStr = nil;
                }else{
                    _locationStr = str;
                    [_base_tableview reloadData];
                }
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
        {
            
            FriendWhoLookViewController *WLVC = [FriendWhoLookViewController new];
            WLVC.jump = ^(NSDictionary *dic) {
                NSNumber *type = dic[@"seeType"];
                self.seeType = type.integerValue;
                if (self.seeType == 3||self.seeType == 4) {
                    _userArray = dic[@"friendArray"];
                } else {
                    _userArray = @[];
                }
                [self.base_tableview reloadData];
            };
            [self.navigationController pushViewController:WLVC animated:YES];
        }
            break;
        case 2:
        {
            
            if ([_UserShowStr isEqualToString:@"仅自己可见"]) {
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"可见范围选择私密时，此功能不可使用" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertVC addAction:confirAction];
                [self.navigationController presentViewController:alertVC animated:YES completion:nil];
                
            }else{
                FriendRemindWhoController *SFVC = [FriendRemindWhoController new];
                SFVC.addUserArray = _addUserArray.mutableCopy;
                SFVC.titleString = @"提醒谁看";
                SFVC.selectedFriend = ^(NSArray *friendArray, NSArray *addUserArray) {
                    NSLog(@"friendArray%@",friendArray);
                    _addUserArray = addUserArray;
                    NSMutableArray *nickNameArr = [NSMutableArray array];
                    NSMutableArray *widArray = [NSMutableArray array];
                    NSString *str = @"";
                    for(NSDictionary *dict in friendArray){
                        NSNumber *wid = dict[@"wid"];
                        NSString *nimckN = dict[@"nickName"];
                        [widArray addObject:wid.stringValue];
                        [nickNameArr addObject:nimckN];
                    }
                    str = [widArray componentsJoinedByString:@","];
                    self.atPersonsStr = str;
                    self.atPersionNameStr = [nickNameArr componentsJoinedByString:@","];
                    [self.base_tableview reloadData];
                };
                [self.navigationController pushViewController:SFVC animated:YES];
            }
            
          
        }
            break;
    }
}

#pragma mark -  ===========================pick Vedio===选择相机或者录制=======================
-(void)pickVedio{
    
    if(self.vedioUrl){
        avPlayer = [[AVPlayerViewController alloc] init];
        avPlayer.player = [[AVPlayer alloc] initWithURL:self.vedioUrl];
        avPlayer.videoGravity = AVLayerVideoGravityResizeAspect;
        [self presentViewController:avPlayer animated:YES completion:nil];
   
    }else{
     [self tapClick];
    }
}




- (void)tapClick{
        [self.actionSheetTitle showGGActionSheet];
}

-(GGActionSheet *)actionSheetTitle{
        if (!_actionSheetTitle) {
            
            _actionSheetTitle = [GGActionSheet ActionSheetWithTitleArray:@[@"拍摄",@"从相册中选取"] andTitleColorArray:@[[UIColor blackColor]] delegate:self];
            //取消按钮颜色设置
            _actionSheetTitle.cancelDefaultColor = [UIColor blackColor];
            //如果设置了选项颜色 当颜色数组和标题数组数量对不上时 多余标题使用选项默认颜色
            //如果设置了选项颜色 当颜色数组传空时，所有选项默认使用选项颜色
            //如果没设置选项颜色 数量对不上以及颜色数组为空时都使用默认黑色
            _actionSheetTitle.optionDefaultColor = [UIColor blackColor];
        }
        return _actionSheetTitle;
}


-(void)GGActionSheetClickWithActionSheet:(GGActionSheet *)actionSheet Index:(int)index{

    
    if (index == 1) {
    
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.navigationBar.barTintColor = Colorbackground;
            
            picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            picker.mediaTypes = @[(NSString *)kUTTypeMovie];

            
            [self presentViewController:picker animated:YES completion:^{
                UIViewController *vc = picker.viewControllers.lastObject;
                UIBarButtonItem *bar = [vc valueForKey:@"imagePickerCancelButton"];
                UIButton *btn = [bar valueForKey:@"view"];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [picker.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
                [picker.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
                picker.navigationController.navigationBar.translucent = NO;

            }];

        }

    }else{
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeSavedPhotosAlbum)] && [UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
            picker.mediaTypes = temp_MediaTypes;
            picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
            picker.videoMaximumDuration = 10.0;
            picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
            picker.delegate = self;
            picker.allowsEditing = YES;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate ================录制后回调==========
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    if (self.conversation_Type == KConversationPhoto) {
        
        NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
        
        //当选择的类型是图片
        if ([type isEqualToString:@"public.image"]){
            
            //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出
            UIImage* oldImage = [info objectForKey:UIImagePickerControllerEditedImage];
            
            //图片压缩，因为原图都是很大的，不必要传原图
            
            
            UIImageOrientation imageOrientation = oldImage.imageOrientation;
            
            UIImage * image;
            if(imageOrientation!=UIImageOrientationUp)
            {
                // 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
                // 以下为调整图片角度的部分
                UIGraphicsBeginImageContext(oldImage.size);
                [oldImage drawInRect:CGRectMake(0, 0, oldImage.size.width, oldImage.size.height)];
                image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                // 调整图片角度完毕
            }else{
                image = oldImage;
            }
            NSData *data;
            
            if (UIImagePNGRepresentation(image) == nil){
                data = UIImageJPEGRepresentation(image, 1.0);
            }
            else{
                data = UIImagePNGRepresentation(image);
            }
            
            
            //图片保存的路径
            //这里将图片放在沙盒的documents文件夹中
            NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            
            //文件管理器
            NSFileManager *fileManager = [NSFileManager defaultManager];
            
            //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.jpg
            [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
            [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
            
            UIImage * img = [UIImage imageWithData:data];
            
            [picker dismissViewControllerAnimated:YES completion:nil];
            NSArray *arr = [NSArray array];
            arr = @[img];
            [self.arrM addObjectsFromArray:arr];

        }else{
            NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
            if([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
                NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];//视频路径
                NSString *urlStr=[url path];
                if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
                    self.vedioUrl = url;
                    UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);//保存视频到相簿
                }
            }
        }
    
    
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.base_tableview reloadData];


}


//视频保存后的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"视频错误，请重新拍摄或重新选择"];
    }else{
        self.vedioImageV.image = [HcardHttpmanager thumbnailImageForVideo:self.vedioUrl atTime:0.5];
        
    }
}

@end
